<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Event;

class Product extends Base
{
    protected $name = 'product';

    public function cate1()
    {
        return $this->hasOne(ProductCate::class, 'id', 'cate_1')->field('id,title');
    }

    public function cate2()
    {
        return $this->hasOne(ProductCate::class, 'id', 'cate_2')->field('id,title');
    }
    public function card()
    {
        return $this->hasOne(Card::class, 'id', 'card_id')->field('id,title');
    }
    

    public function getSpecDataAttr($val, $data)
    {
        return $data['spec'] ? json_decode($data['spec'], true) : [];
    }

    public static function productDelete($param, $logs): array
    {
        try {
            if (is_array($param['id'])) {
                self::destroy($param['id']);
                $model = (object)[];
                $logs['operation'] = 'deleteAll';
                $model->ids = $param['id'];
            } else {
                $model = self::where($logs['pk'], $param['id'])->find();
                self::destroy($param['id']);
                $logs['operation'] = 'delete';
            }
            if ($logs['writeLog']) {
                $logs['model'] = $model;
                Event::trigger('Logs', $logs);
            }

            ProductSpec::destroy(['pid' => $param['id']], true);
            return ['code' => 1, 'msg' => '已删除'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function _save($param, $logs): array
    {
        parent::startTrans();
        try {

            if (!empty($param['images'])) {
                $param['icon'] = explode(',', $param['images'])[0];
            }
            if (!empty($param['id'])) {
                $product = parent::update($param);
                $product->operation = 'save';
            } else {
                $param['initOk'] = 'true';
                $product = parent::create($param);
                $product->operation = 'create';
            }
            if ($param['spec_open'] == 2 && $param['initOk'] == 'true') {
                $specVale = [];
                $min = [];
                $stock = 0;
                $stockFiled = '';
                foreach ($param['tableSpec'] as $value) {
                    $mergeId = [];
                    $mergeTitle = [];
                    foreach ($value as $k => $item) {
                        $title = explode('spec$$Title_', $k);
                        if (count($title) > 1) {
                            $mergeId[] = $title[1];
                            $mergeTitle[] = $item;
                        }
                    }
                    $tapeVale = [];
                    foreach ($param['tape'] as $tape) {
                        $tapeVale[$tape['field']] = $value[$tape['field']];
                        if (empty($tape['type'])) {
                            if (empty($min[$tape['field']])) {
                                $min[$tape['field']] = $value[$tape['field']];
                            } else {
                                $min[$tape['field']] = $value[$tape['field']] < $min[$tape['field']] ? $value[$tape['field']] : $min[$tape['field']];
                            }
                        } else if ($tape['type'] == 'stock') {
                            $stockFiled = $tape['field'];
                            $stock += intval($value[$tape['field']]);
                        }
                    }
                    $mergeVale = [
                        'pid'         => $product->id,
                        'icon'        => $value['icon'],
                        'merge_id'    => implode(',', $mergeId),
                        'merge_title' => implode(',', $mergeTitle)
                    ];
                    $specVale[] = array_merge($tapeVale, $mergeVale);
                }

                //清除旧规格
                if (!empty($param['id'])) {
                    ProductSpec::destroy(['pid' => $param['id']], true);
                }
                //填写新规格
                (new ProductSpec())->insertAll($specVale);

                $product->spec = json_encode($param['spec']);
                $product->table_spec = json_encode($param['tableSpec']);
                foreach ($min as $k => $v) {
                    $product->$k = $v;
                }
                $product->$stockFiled = $stock;
                $product->save();
            }

            parent::commit();
            Event::trigger('Logs', $product);
            return ['code' => 1, 'msg' => '已保存'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


}
